package Controller.UserController;

import Model.User;
import Service.UserService;
import Service.UserServiceImpl;
import Utils.ServiceFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author zyp
 * date 2022-03-08
 */
@WebServlet("/login.do")
public class LoginServlet extends HttpServlet {
    UserService userService = ServiceFactory.getUserService();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String type = req.getParameter("type");

        User user = new User();
        user.setUsername(username);
        user.setPassword(password);

        if (!(type.equals("0") || type.equals("1"))) {
            resp.getWriter().println("<script> alert('对不起，登录异常，请重新登录');window.location.href='/index.html' </script>");
        } else {
            if (userService.login(user, req.getSession())) {
                if (type.equals("0")) {
                    resp.getWriter().println("<script> alert('恭喜您登陆成功');window.location.href='/front-page/index.html' </script>");
                } else if (type.equals("1")) {
                    resp.getWriter().println("<script> alert('恭喜您登陆成功');window.location.href='/back-page/main.html' </script>");
                }
            } else {
                resp.getWriter().println("<script> alert('对不起，登录异常，请重新登录');window.location.href='/index.html' </script>");
            }
        }
    }
}
